<template>
  <div>
    <el-row style="display: flex; justify-content: center;">
      <!-- 左侧：个人信息 -->
      <el-col :span="10">
        <div class="xw-block" style="height: 600px; overflow-y: auto;">
          <el-form style="padding: 35px">
            <!-- 用户头像 -->
            <el-form-item style="text-align: center;">
              <el-upload
                  class="avatar-uploader"
                  :action="baseUrl + '/file/upload'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess">
                <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <div style="height: 260px;overflow-y: scroll">
              <!-- 用户昵称 -->
              <el-form-item label="昵称">
                <el-input style="width: 85%" v-model="form.nickName"></el-input>
              </el-form-item>

              <!-- 用户邮箱 -->
              <el-form-item label="邮箱" v-if="form.role === 'ROLE_USER' || form.role === 'ROLE_ADMIN'">
                <el-input style="width: 85%"  v-model="form.email"></el-input>
              </el-form-item>

              <!-- 用户年龄 -->
              <el-form-item label="年龄" v-if="form.role === 'ROLE_USER' || form.role === 'ROLE_ADMIN'">
                <el-input style="width: 85%"  type="number" v-model="form.age"></el-input>
              </el-form-item>

              <!-- 用户手机号 -->
              <el-form-item label="电话">
                <el-input style="width: 85%"  v-model="form.phone"></el-input>
              </el-form-item>
            </div>

          </el-form>
          <div style="width: 100%;text-align: center">
            <el-button type="primary" style="width: 80%" @click="updatePersonInfo">确认修改</el-button>
          </div>
        </div>

      </el-col>

      <!-- 右侧：收藏和点赞 -->
      <el-col :span="10" style="margin-left: 20px;">
        <div class="xw-block" style="height: 600px; overflow-y: auto;">
          <el-tabs type="card" v-model="activeTab" @tab-click="handleTabClick">
            <!-- 我的帖子 -->
            <el-tab-pane label="我的帖子" name="0">
              <el-table :data="postData" border>
                <el-table-column label="帖子标题">
                  <template slot-scope="scope">
                    <!-- 只显示帖子标题 -->
                    <h4 class="ellipsis xw-enlarge"
                        @click="topostDetail(scope.row)"
                        style="cursor: pointer;
                        color: #409EFF;
                        font-weight: bold;">
                      {{ scope.row.title }} <!-- 只显示标题 -->
                    </h4>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button icon="el-icon-edit" type="text" @click="edit(scope.row.title)">编辑</el-button>
                    <el-popconfirm
                        title="这是一段内容确定删除吗？"
                        @confirm="delpost(scope.row.id)"
                    >
                      <el-button slot="reference" icon="el-icon-delete" type="text" style="margin-left: 10px;">删除</el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                  @size-change="handleCollectionSizeChange"
                  @current-change="handleCollectionCurrentChange"
                  :page-sizes="pageSizeArr"
                  :page-size="pageRequest.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCollection">
              </el-pagination>
            </el-tab-pane>


            <!-- 我的收藏 -->
            <el-tab-pane label="我的收藏" name="1">
              <el-table :data="collectionData" border>
                <el-table-column label="收藏项目">
                  <template slot-scope="scope">
                    <h4 class="ellipsis xw-enlarge"
                        @click="toDetail(scope.row)"
                        style="cursor: pointer; color: #409EFF; font-weight: bold;">
                      {{ scope.row.title }}
                    </h4>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-popconfirm
                        style="margin-left: 5px"
                        confirm-button-text="确定"
                        cancel-button-text="我再想想"
                        icon="el-icon-info"
                        icon-color="red"
                        title="您确定要删除吗？"
                        @confirm="del(scope.row.id)">
                      <el-button slot="reference" size="small">取消收藏</el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                  @size-change="handleCollectionSizeChange"
                  @current-change="handleCollectionCurrentChange"
                  :page-sizes="pageSizeArr"
                  :page-size="pageRequest.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCollection">
              </el-pagination>
            </el-tab-pane>

            <!-- 我的点赞 -->
            <el-tab-pane label="我的点赞" name="2">
              <el-table :data="likeData" border>
                <el-table-column label="点赞项目">
                  <template slot-scope="scope">
                    <h4 class="ellipsis xw-enlarge"
                        @click="toDetail(scope.row)"
                        style="cursor: pointer; color: #409EFF; font-weight: bold;">
                      {{ scope.row.title }}
                    </h4>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-popconfirm
                        style="margin-left: 5px"
                        confirm-button-text="确定"
                        cancel-button-text="我再想想"
                        icon="el-icon-info"
                        icon-color="red"
                        title="您确定要取消点赞吗？"
                        @confirm="del(scope.row.id)">
                      <el-button slot="reference" size="small">取消点赞</el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :page-sizes="pageSizeArr"
                  :page-size="pageRequest.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalLikes">
              </el-pagination>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>

    <my-drawer ref="MyDrawer" :row="selectRow" @saveOrUpdate="update">
      <template #default>
        <el-form label-position="top" class="post-form">
          <el-form-item label='标题'>
            <el-input placeholder='请输入发布的帖子标题'
                      v-model='selectRow.title'></el-input>
          </el-form-item>
          <el-form-item label="帖子类型">
            <el-select v-model="selectRow.type" placeholder="请选择帖子类型">
              <el-option label="C语言" value="C语言"></el-option>
              <el-option label="HTML" value="HTML"></el-option>
              <el-option label="JAVA" value="JAVA"></el-option>
              <el-option label="Python" value="Python"></el-option>
              <el-option label="云计算" value="云计算"></el-option>
              <el-option label="软件工程" value="软件工程"></el-option>
              <el-option label="计算机科学与技术" value="计算机科学与技术"></el-option>
              <el-option label="信息安全" value="信息安全"></el-option>
              <el-option label="大数据" value="大数据"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label='发布内容'>
            <vue-editor v-model="selectRow.content"></vue-editor>
          </el-form-item>
        </el-form>
      </template>
    </my-drawer>
  </div>
</template>

<script>
import MyDrawer from "@/components/MyDrawer.vue";
import {VueEditor} from "vue2-editor";

export default {
  data() {
    return {
      form: {},              // 个人信息表单
      baseUrl: '',           // 基础 URL
      activeTab: '0',        // 当前激活的标签，默认展示“我的帖子”
      collectionData: [],    // 收藏数据
      likeData: [],          // 点赞数据
      postData: [],          // 用户发布的帖子数据
      totalLikes: 0,         // 点赞数据总数
      totalCollection: 0,    // 收藏数据总数
      totalPosts: 0,         // 帖子总数
      pageSizeArr: [10, 20, 30, 40],  // 每页大小选项
      selectRow: {
        title: '',
        type: '',
        content: ''
      }, // 用于存储选中的文章
      pageRequest: {         // 分页请求参数
        pageNum: 1,          // 当前页码
        pageSize: 10,        // 每页显示条数
        q: {
          type: 1
        }       // 点赞类型（0代表点赞）
      },
      user: {}               // 当前登录用户信息
    }
  },
  components: {
    MyDrawer,
    VueEditor
  },
  mounted() {
    this.getPersonInfo();    // 获取个人信息
    this.baseUrl = this.baseURL();  // 设置基础 URL
    this.getMyCollection();  // 默认加载收藏数据
    this.getMyLikes();       // 默认加载点赞数据
    this.getMyPosts();       // 默认加载发布的帖子数据

    // 从 localStorage 中读取分页状态
    const collectionPage = localStorage.getItem('collectionPage');
    const likesPage = localStorage.getItem('likesPage');
    if (collectionPage) this.pageRequest.pageNum = parseInt(collectionPage);
    if (likesPage) this.pageRequest.pageNum = parseInt(likesPage);
  },
  methods: {
    toDetail(item) {
      this.$router.push({name: 'PostCodeDetail', params: {id: item.linkId}});

    },
    topostDetail(item) {
       this.$router.push({name: 'PostCodeDetail', params: {id: item.id}});

    },
    edit(title) {
      // 根据标题查找文章并进行编辑
      const post = this.postData.find(item => item.title === title);
      if (post) {
        this.selectRow = post;  // 将选中的帖子信息赋值给 selectRow
        this.$refs.MyDrawer.open(this.selectRow);  // 打开 MyDrawer 并传递选中的文章信息
      }
    },
    update() {
      this.request.post("/postCode", this.selectRow).then(res => {
        if (res.code === '200') {
          this.messageSuccess("修改成功");
          this.$refs.MyDrawer.close();  // 关闭抽屉
          this.getMyPosts();  // 重新加载数据
        } else {
          this.messageError(res.msg);  // 显示错误消息
        }
      });
    },
    updatePersonInfo() {
      this.request.post("/web/updatePersonInfo", this.form).then(res => {
        if (res.code === '200') {
          this.getPersonInfo();
          this.messageSuccess("修改成功");
          // 更新缓存的信息
          let user = JSON.parse(localStorage.getItem("user"));
          user.imageUrl = this.form.imageUrl;
          user.nickName = this.form.nickName;
          localStorage.setItem("user", JSON.stringify(user));
        } else {
          this.messageError(res.msg);
        }
      });
    },
    getPersonInfo() {
      this.request.get("/web/getPersonInfo").then(res => {
        if (res.code === '200') {
          this.form = res.data;
          this.user = res.data; // 保存当前用户信息
        }
      });
    },
    getMyCollection() {
      this.pageRequest.q.type = 2
      this.request.post("/thumbs/page", this.pageRequest).then(res => {
        if (res.code === '200') {
          this.collectionData = res.data.list;
          this.totalCollection = res.data.total;
        }
      });
    },
    del(id) {
      this.request.delete("/thumbs/" + id).then(res => {
        if (res.code === '200') {
          this.messageSuccess("删除成功");
          this.getMyCollection();
          this.getMyLikes();
        } else {
          this.messageError("删除失败");
        }
      });
    },
    delpost(id) {
      this.request.delete(`/postCode/${id}`).then(res => {
        if (res.code === '200') {
          this.messageSuccess("删除成功");
          this.getMyPosts();
        } else {
          this.messageError("删除失败");
        }
      });
    },
    getMyLikes() {
      this.pageRequest.q.type = 0;
      this.request.post("/thumbs/page", this.pageRequest).then(res => {
        if (res.code === '200') {
          this.likeData = res.data.list;
          this.totalLikes = res.data.total;
        }
      });
    },
    getMyPosts() {
      this.request.get("postCode/getMyPosts").then(res => {
        if (res.code === '200') {
          // 筛选出用户发布的帖子，并提取标题
          this.postData = res.data
          this.totalPosts = this.postData.length;  // 更新帖子总数
        } else {
          this.messageError("获取帖子失败");
        }
      }).catch(error => {
        this.messageError("请求失败：" + error.message);
      });
    },

    handleTabClick(tab) {
      // 只有点击时才加载相应数据
      if (tab.name === '0') {
        this.getMyPosts();  // 加载帖子
      } else if (tab.name === '1') {
        this.getMyCollection();  // 加载收藏
      } else if (tab.name === '2') {
        this.getMyLikes();  // 加载点赞
      }
    },
    handleAvatarSuccess(e) {
      if (e.code === '200') {
        this.form.imageUrl = e.data;
      }
    },
// 收藏分页数据变化时保存
    handleCollectionSizeChange(size) {
      this.pageRequest.pageSize = size;
      localStorage.setItem('collectionPage', this.pageRequest.pageNum); // 保存分页信息
      this.getMyCollection();
    },
    handleCollectionCurrentChange(pageNum) {
      this.pageRequest.pageNum = pageNum;
      localStorage.setItem('collectionPage', pageNum); // 保存分页信息
      this.getMyCollection();
    },
// 点赞分页数据变化时保存
    handleSizeChange(size) {
      this.pageRequest.pageSize = size;
      localStorage.setItem('likesPage', this.pageRequest.pageNum); // 保存分页信息
      this.getMyLikes();
    },
    handleCurrentChange(pageNum) {
      this.pageRequest.pageNum = pageNum;
      localStorage.setItem('likesPage', pageNum); // 保存分页信息
      this.getMyLikes();
    },
  }
}
</script>